# @FileName  : conf.py
# @Time      : 2025/3/6 04:46
# @Author    : LuZhaoHui
# @Software  : PyCharm

from configparser import ConfigParser


class MyParser(ConfigParser):
    # Inherit from built-in class: ConfigParser

    def optionxform(self, option_str):
        # Rewrite without lower()
        return option_str


class MainConf:
    # 配置
    varConf = {
        'Title': '大模型在线测试',
        'DataPath': '',
        'ResultPath': '',
        'WindowMax': False,
    }
    varModel = {
        'IsvLLM': True,
        'IsOpenAI': False,
        'BaseUrlRequest': '',
        'BaseUrlOpenAI': '',
        'IsApiKey': True,
        'ApiKey': '',
        'ReqType': '',
        'IsStream': False,
        'ReqStream': False,
        'CurModel': 0,
        'ModelList': [],
        'ModelNameList': [],
        'CurSystemPrompt': 0,
        'SystemPromptList': [],
        'IsGetUserInFo': False,
    }
    varPara = {
        'max_tokens':1024,          #最大TOKEN数,控制生成的内容的长度;
        'temperature':0.7,          #温度;0.0-1.5..;控制输出文本的随机性;
        'top_p':0.7,                #核采样;0.0-1.0；控制模型选择的概率范围;
        'top_k':40,                 #前K采样;1-~;限制模型每次选择时考虑的候选词数，防止低概率词出现
        'presence_penalty':0.0,     #控制生成文本中是否包含新话题;-2.0-2.0;
        'frequency_penalty':0.0,    #频率惩罚,减少重复;-2.0-2.0;
        'n':1,                      #回复数量
        'response_format':'json',   #输出格式，json,text
    }
    varReason = {
        'ImagePage': 'A4',
        'CurDir': '',
        'DirType': '',
        'CurPrompt': '',
        'PromptListNums': 10,
        'PromptList': [],
    }
    varMysql = {
        'IsMysql': False,
        'MysqlHost': '127.0.0.1',
        'MysqlPort': 3306,
        'MysqlUser': 'root',
        'MysqlPass': 'root',
        'MysqlDatabase': 'LLM',
    }
    vars = {
        'CONF': varConf,
        'MODEL': varModel,
        'PARA': varPara,
        'REASON': varReason,
        'MYSQL': varMysql
    }

    def __init__(self, file):
        self.config = MyParser()
        self.name = file
        self.read()

    def get(self, section, key):
        return self.config.get(section, key)

    def read(self):
        self.config.read(self.name, 'utf-8')
        # 取配置
        for key, vs in self.vars.items():
            # print("%s:%s" % (key, vars))
            for k, v in vs.items():
                # print("%s:%s" % (key, k))
                s = self.get(key, k)
                if isinstance(vs[k], bool):
                    vs[k] = bool(eval(s))
                elif isinstance(vs[k], int):
                    vs[k] = int(s)
                elif isinstance(vs[k], float):
                    vs[k] = float(s)
                elif isinstance(vs[k], list):
                    vs[k] = s.split(',')
                else:
                    vs[k] = s

    def write(self, section, key, value):
        self.config.set(section, key, str(value))
        with open(self.name, 'w', encoding='utf-8') as f:
            self.config.write(f)

